package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.*;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.dto.UserDto;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import com.itheima.ydd.service.Sys_UserService;
import com.sun.media.jfxmediaimpl.HostUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("sys_user")
public class Sys_UserController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private Sys_UserService sys_userService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @GetMapping("list")
    public R list(String login_name, Integer status, String phone, int page, int limit) {
        Page<SysUser> sysUserPage = new Page<>(page, limit);
        Page<UserDto> userDtoPage = new Page<>();
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(login_name), SysUser::getLoginName, login_name);
        lqw.eq(status != null, SysUser::getStatus, status);
        lqw.like(StringUtils.isNotEmpty(phone), SysUser::getPhone, phone);
        lqw.orderByDesc(SysUser::getUpdateDate);
        sys_userService.page(sysUserPage, lqw);
        BeanUtils.copyProperties(sysUserPage, userDtoPage, "records");
        List<SysUser> records = sysUserPage.getRecords();
        List<UserDto> list = new ArrayList<>();
        for (SysUser sysUser : records) {
            ArrayList<String> role_id = new ArrayList<>();
            ArrayList<String> roleNameList = new ArrayList<>();
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(sysUser, userDto);
            String roleId = sysUser.getRoleId();
            String[] split = roleId.substring(1, roleId.length() - 1).split(",");
            for (String s : split) {
                s = s.substring(1, s.length() - 1);
                role_id.add(s);
                String name = iSysRoleService.getById(s).getName();
                if (name != null) {
                    roleNameList.add(name);
                }
            }
            userDto.setRolename(roleNameList);
            userDto.setRole_id(role_id);
            list.add(userDto);
        }
        userDtoPage.setRecords(list);
        R r = R.success("totalPages", (int) userDtoPage.getPages());
        r.putData("pageSize", (int) userDtoPage.getSize());
        r.putData("count", (int) userDtoPage.getTotal());
        r.putData("currentPage", (int) userDtoPage.getCurrent());
        r.putData("data", userDtoPage.getRecords());

        return r;
    }



    @PostMapping("add")
    public ResultData add(@RequestBody UserDto userDto) {
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getLoginName, userDto.getLoginName());
        SysUser sysUser = sys_userService.getOne(lqw);
        if (sysUser != null) {
            throw new BusinessException("账号名已存在");
        }
        List<String> role_id = userDto.getRole_id();
        String roleId = "[";
        for (int i = 0; i < role_id.size(); i++) {
            roleId += "\"" + role_id.get(i) + "\"";
            if (i == role_id.size() - 1) {
                roleId += "]";
                continue;
            }
            roleId += ",";
        }
        userDto.setRoleId(roleId);
        String s = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
        userDto.setPassword(s);
        userDto.setCreateDate(LocalDateTime.now());

        userDto.setId(UUID.randomUUID().toString());
        sys_userService.saveUser(userDto);
        return ResultData.ok("添加成功", "");
    }

    @GetMapping("rowInfo")
    public ResultData rowInfo(String id) {
        SysUser sysUser = sys_userService.getById(id);
        ArrayList<String> role_id = new ArrayList<>();
        ArrayList<String> roleNameList = new ArrayList<>();
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(sysUser, userDto);
        String roleId = sysUser.getRoleId();
        String[] split = roleId.substring(1, roleId.length() - 1).split(",");
        for (String s : split) {
            s = s.substring(1, s.length() - 1);
            role_id.add(s);
            String name = iSysRoleService.getById(s).getName();
            if (name != null) {
                roleNameList.add(name);
            }
        }
        userDto.setRolename(roleNameList);
        userDto.setRole_id(role_id);
        return ResultData.ok("查询成功", userDto);
    }

    @PostMapping("update")
    public ResultData update(@RequestBody UserDto userDto) {
        SysUser sysUser = sys_userService.getById(userDto.getId());
        if (userDto.getLoginName() != null) {
            if (!sysUser.getLoginName().equals(userDto.getLoginName())) {
                LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SysUser::getLoginName, userDto.getLoginName());
                SysUser one = sys_userService.getOne(lqw);
                if (one != null) {
                    throw new BusinessException("更改的账户名已存在");
                }
            }
        }
        if (userDto.getPassword() != null) {
            if (!sysUser.getPassword().equals(userDto.getPassword())) {
                String s = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
                userDto.setPassword(s);
            }
        }

        String roleId = sysUser.getRoleId();
        String[] split = roleId.substring(1, roleId.length() - 1).split(",");
        for (String s : split) {
            s = s.substring(1, s.length() - 1);
            if (iSysRoleService.getById(s).getSuperadmin() == 1 && sysUser.getStatus() != userDto.getStatus()) {
                throw new BusinessException("该账号是超级管理员账号,不可冻结");
            }
        }
        if (userDto.getRole_id() != null) {
            List<String> role_id = userDto.getRole_id();
            String roleId01 = "[";
            for (int i = 0; i < role_id.size(); i++) {
                roleId01 += "\"" + role_id.get(i) + "\"";
                if (i == role_id.size() - 1) {
                    roleId01 += "]";
                    continue;
                }
                roleId01 += ",";
            }
            userDto.setRoleId(roleId01);
        }
        sys_userService.updateById(userDto);
        return ResultData.ok("修改成功", "");
    }









        /*String roleId01 = sysUser.getRoleId();
        String[] split = roleId01.substring(1, roleId01.length() - 1).split(",");
        for (String s : split) {
            s = s.substring(1, s.length() - 1);
            if (iSysRoleService.getById(s).getSuperadmin() == 1) {
                throw new BusinessException("该账号是超级管理员账号,不可冻结");
            }
        }
        if (userDto.getRole_id() != null) {
            List<String> role_id = userDto.getRole_id();
            String roleId = "[";
            for (int i = 0; i < role_id.size(); i++) {
                roleId += "\"" + role_id.get(i) + "\"";
                if (i == role_id.size() - 1) {
                    roleId += "]";
                    continue;
                }
                roleId += ",";
            }
            userDto.setRoleId(roleId);
        }
        if (userDto.getPassword() != null) {
            String s = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
            userDto.setPassword(s);
        }
        sys_userService.updateById(userDto);
        return ResultData.ok("修改成功", "");*/
//}

    @GetMapping("del")
    public ResultData del(String id) {
        SysUser sysUser = sys_userService.getById(id);
        String roleId = sysUser.getRoleId();
        String[] split = roleId.substring(1, roleId.length() - 1).split(",");
        for (String s : split) {
            s = s.substring(1, s.length() - 1);
            if (iSysRoleService.getById(s).getSuperadmin() == 1) {
                throw new BusinessException("该账号是超级管理员账号,不可删除");
            }
        }
        sys_userService.removeById(id);
        return ResultData.ok("删除成功", "");
    }
}
